<h1>Go FAQ 101</h1>

<p><i>
(This is an unofficial Go FAQ. The official one is <a href="https://golang.org/doc/faq">here</a>.)
</i></p>

<div>
Index:

<ul class="summaries" id="unofficial-faq.html">
<li>compiler and runtime
	<ul class="index">
	<li><a class="index" href="#error-non-name">What does the compile error message <code>non-name *** on left side of :=</code> mean?</a></li>
	<li><a class="index" href="#error-missing-left-brace">What does the compile error message <code>unexpected newline, expecting { after if clause</code> mean?</a></li>
	<li><a class="index" href="#error-declared-not-used">What does the compiler error message <code>declared and not used</code> mean?</a></li>
	<li><a class="index" href="#map-iteration-order">Does Go runtime maintain the iteration orders for maps?</a></li>
	<li><a class="index" href="#compiler-field-padding">Will Go compilers do padding to ensure field alignments for struct types?</a></li>
	<li><a class="index" href="#final-zero-size-field">Why does the final field of a zero-sized type in a struct contribute to the size of the struct sometimes?</a></li>
	<li><a class="index" href="#new-function">Is <code>new(T)</code> a sugar of <code>var t T; (&amp;t)</code>?</a></li>
	<li><a class="index" href="#fatal-error-deadlock">What does the runtime error message <code>all goroutines are asleep - deadlock</code> mean?</a></li>
	<li><a class="index" href="#64-bit-alignment">Are 64-bit integer values guaranteed to be 64-bit aligned
		so that they can be accessed atomically?</a></li>
	<li><a class="index" href="#atomical-assignment">Are assignments of values atomic operations?</a></li>
	<li><a class="index" href="#zero-values-zero-bytes">Is every zero value composed of a sequence of zero bytes in memory?</a></li>
	<li><a class="index" href="#function-inline">Does the standard Go compiler support function inline?</a></li>
	<li><a class="index" href="#finalizers">Can I use finalizers as object destructors?</a></li>
	</ul>
</li>

<li>standard packages
	<ul class="index">
	<li><a class="index" href="#get-days-of-month">How to get the number of days of any month by using as few code lines as possible?</a></li>
	<li><a class="index" href="#time-sleep-after">What is the difference between the function call <code>time.Sleep(d)</code> and the channel receive operation <code>&lt;-time.After(d)</code>?</a></li>
	<li><a class="index" href="#trim">Calls of the <code>TrimLeft</code> and <code>TrimRight</code> functions in the <code>strings</code> and <code>bytes</code>
		standard packages often return unexpected results, are there bugs in these function implementations?</a></li>
	<li><a class="index" href="#fmt-print-println">What are the differences between the <code>fmt.Print</code> and <code>fmt.Println</code> functions?</a></li>
	<li><a class="index" href="#log-print-println">Is there any difference between the <code>log.Print</code> and <code>log.Println</code> functions?</a></li>
	<li><a class="index" href="#fmt-print-synced">Are <code>fmt.Print</code>, <code>fmt.Println</code> and <code>fmt.Printf</code> functions synchronized?</a></li>
	<li><a class="index" href="#print-builtin-fmt-log">What are the differences between the built-in <code>print</code>/<code>println</code> functions and the corresponding print functions in the <code>fmt</code> and <code>log</code> standard packages?</a></li>
	<li><a class="index" href="#math-crypto-rand">What is the difference between the random numbers produced by the <code>math/rand</code> standard package and the <code>crypto/rand</code> standard package?</a></li>
	<li><a class="index" href="#math-round">Why isn't there a <code>math.Round</code> function?</a></li>
	</ul>
</li>

<li>type system
	<ul class="index">
	<li><a class="index" href="#incomparable-types">Which types don't support comparisons?</a></li>
	<li><a class="index" href="#nil-equality">Why aren't two <code>nil</code> values equal sometimes?</a></li>
	<li><a class="index" href="#slice-conversion">Why don't type <code>[]T1</code> and <code>[]T2</code> share the same underlying type
		even if the two different types <code>T1</code> and <code>T2</code> share the same underlying type?</a></li>
	<li><a class="index" href="#unaddressable-values">Which values can and which values can't be taken addresses?</a></li>
	<li><a class="index" href="#maps-are-unaddressable">Why are map elements not addressable?</a></li>
	<li><a class="index" href="#slice-elements-always-addressable">Why elements of a non-nil slice are always addressable, even if the slice is unaddressable?</a></li>
	<li><a class="index" href="#method-set-relation">For any non-pointer non-interface defined type <code>T</code>,
		why is the method set of <code>*T</code> always a super set of the method set of <code>T</code>,
		but not vice versa?</a></li>
	<li><a class="index" href="#types-can-have-methods">Which types can we implement methods for?</a></li>
	<li><a class="index" href="#declare-immutables">How to declare immutable values in Go?</a></li>
	<li><a class="index" href="#set-container-type">Why isn't there a built-in <code>set</code> container type?</a></li>
	<li><a class="index" href="#byte-rune-slice-string">What is byte? What is rune?
		How to convert <code>[]byte</code> and <code>[]rune</code> values to strings?</a></li>
	<li><a class="index" href="#pointer-atomic">How to manipulate pointer values atomically?</a></li>
	</ul>
</li>
<li>others
	<ul class="index">
	<li><a class="index" href="#about-iota">What does <code>iota</code> mean?</a></li>
	<li><a class="index" href="#check-if-channels-closed">Why isn't there a built-in <code>closed</code> function to check whether or not a channel is closed?</a></li>
	<li><a class="index" href="#return-local-pointers">Is it safe for a function to return pointers of local variables?</a></li>
	<li><a class="index" href="#gopher">What does the word <b><i>gopher</i></b> mean in Go community?</a></li>
	</ul>
</li>


</ul>
</div>



<div class="summaries-items">

<!-- compiler and runtime  -->

<a class="anchor" id="error-non-name"></a>
<h3>
	What does the compile error message <code>non-name *** on left side of :=</code> mean?
</h3>

Up to now (Go 1.13), there is <a href="https://golang.org/ref/spec#Short_variable_declarations">a mandatory rule</a>
for short variable declarations:
<div class="alert alert-success">
All items at the left side of <code>:=</code> must be pure
<a href="https://golang.org/ref/spec#Identifiers">identifiers</a> and at least one of them must be a new variable name.
</div>

<p>
This means container elements (<code>x[i]</code>),
struct fields (<code>x.f</code>), pointer dereferences (<code>*p</code>)
and qualified identifiers (<code>aPackage.Value</code>)
can't appear at the left side of <code>:=</code>.
</p>

<p>
Currently, there is an <a href="https://github.com/golang/go/issues/377">open issue</a>
(which was merged with <a href="https://github.com/golang/go/issues/6842">a more related one</a>)
for this problem. It looks Go authors want to leave this problem unresolved until Go 2.0.
</p>

<a class="anchor" id="error-missing-left-brace"></a>
<h3>
	What does the compile error message <code>unexpected newline, expecting { ...</code> mean?
</h3>

<div>
<p>
In Go, we can't break a code line at an arbitrary position.
Please read <a href="line-break-rules.html">line break rules in Go </a> for details.
By the rules, generally, it is not okay to break code lines just before the open brackets.
</p>

For example, the following code

<pre class="line-numbers"><code class="language-go">if true
{
}

for i := 0; i < 10; i++
{
}

var _ = []int
{
	1, 2, 3
}
</code></pre>

will be interpreted as

<pre class="line-numbers"><code class="language-go">if true;
{
}

for i := 0; i < 10; i++;
{
}

var _ = []int;
{
	1, 2, 3;
}
</code></pre>

Go compilers will report an error for each open bracket <code>{</code>.
To avoid these errors, we should rewrite the above code as the following.

<pre class="line-numbers"><code class="language-go">if true {
}

for i := 0; i < 10; i++ {
}

var _ = []int {
	1, 2, 3,
}
</code></pre>

</div>

<a class="anchor" id="error-declared-not-used"></a>
<h3>
	What does the compiler error message <code>declared and not used</code> mean?
</h3>

<div>
<p>
For the standard Go compiler, each variable declared in local code blocks
must be used as a r-value (right-hand-side value) for at least once.
</p>

So the following code fails to compile.

<pre class="line-numbers"><code class="language-go">func f(x bool) {
	var y = 1 // y declared but not used (as r-values)
	if x {
		y = 2 // here y is used as a left-hand-side value
	}
}
</code></pre>

<!--
exception: https://github.com/golang/go/issues/8560
-->

</div>


<a class="anchor" id="map-iteration-order"></a>
<h3>
	Does Go runtime maintain the iteration orders for maps?
</h3>

<p>
No. <a href="https://golang.org/ref/spec#For_range">Go 1 specification</a>
says the iteration order over a map is not specified and
is not guaranteed to be the same from one iteration to the next.
For the standard Go compiler, the map iteration orders are some randomized.
If you require a stable iteration order for a map you must maintain the order by yourself.
Please read <a href="https://blog.golang.org/go-maps-in-action#TOC_7.">Go maps in action</a> for more information.
</p>

<p>
However, please note, since Go 1.12, the entry order in the print result
of the print functions in standard packages are always ordered.
</p>

<a class="anchor" id="compiler-field-padding"></a>
<h3>
	Will Go compilers do padding to ensure field alignments for struct types?
</h3>

<p>
At least for the standard Go compiler and gccgo, the answer is yes.
How many bytes will be padded is OS and compiler dependent.
Please read <a href="memory-layout.html#size-and-padding">memory layouts</a> for details.
</p>

<!--
<div>
For example, the standard Go compiler will pad bytes
like the following comments describes.
<pre class="line-numbers"><code class="language-go">type T1 struct {
	a int8
	// 7 bytes padded on 64bit OS and pad 3 bytes padded on i386 OS here
	b int64
	c int16
	// 6 bytes padded on AMD64 OS and pad 2 bytes padded on i386 OS here
}

type T2 struct {
	a int8
	// 1 byte padded on both AMD64 and i386 OS here
	c int16
	// 4 bytes padded on AMD64 OS here. No padding on i386 OS
	b int64
}
</code></pre>
<p>
The addresses of <code>T1.b</code> values in memory must be 8-byte aligned on AMD64 OS
and 4-byte aligned on i386 OS, this is why there will be 7 bytes padded on AMD64 OS and
3 bytes padded on i386 OS after <code>T1.a</code>.
</p>
<p>
Go specification makes <a href="https://golang.org/ref/spec#Size_and_alignment_guarantees">some guarantees for type alignments</a>.
One of them is the alignment of a struct type is its largest alignment of its field types.
So <code>T1</code> is also 8-byte aligned on AMD64 OS and 4-byte aligned on i386
(same as type of <code>T1.b</code>, <code>int64</code>),
and the standard Go compiler will ensure the size of values of a type is a multiple of the alignment guarantee of the type,
this is why there will be 6 bytes padded on AMD64 OS and 2 bytes
padded on i386 OS at the end of <code>T1</code> values.
</p>
<p>
The orders of the fields in a struct will affect padding, and padding will affect the size of the struct afterwards.
On AMD64 OS, the size of <code>T1</code> values is 24, but the size of <code>T2</code> values is 16.
</p>
</div>
-->

<p>
Go Compilers will not rearrange struct fields to minimize struct value sizes.
Doing this may cause some unexpected results.
However, programmers can minimize padding by reordering the fields manually.
</p>

<a class="anchor" id="final-zero-size-field"></a>
<h3>
	Why does the final field of a zero-sized type in a struct contribute to the size of the struct sometimes?
</h3>

<!--
https://github.com/golang/go/issues/9401
-->

<div>

<p>
In the current standard Go runtime implementation,
if a memory block is referenced by at least one active pointer,
then the memory block will not be viewed as garbage and will not be collected for sure.
</p>

<p>
All the fields of an addressable struct value can be taken addresses.
If the size of the final field in a non-zero-sized struct value is zero, then taking the address of
the final field in the struct value will return an address which is beyond the allocated memory block
for the struct value. The returned address may point to another allocated memory block
which closely follows the one allocated for the non-zero-sized struct value.
As long as the returned address is stored in an active pointer value,
the other allocated memory block will not get garbage collected, which may cause memory leaking.
</p>

<p>
To avoid the problems, the standard Go compiler will ensure that taking the address of
the final field in a non-zero-sized struct will never return an address which is beyond
the allocated memory block for the struct.
The standard Go compiler implements this by padding some bytes after the final zero-sized field
when needed.
</p>

<p>
If the types of all fields in a struct type are zero-sized
(so the struct is also a zero-sized type), then there is no need to pad bytes in the struct,
for the standard Go compiler treats zero-sized memory blocks specially.
</p>

An example:
<pre class="line-numbers"><code class="language-go">package main

import (
	"unsafe"
	"fmt"
)

func main() {
	type T1 struct {
		a struct{}
		x int64
	}
	fmt.Println(unsafe.Sizeof(T1{})) // 8

	type T2 struct {
		x int64
		a struct{}
	}
	fmt.Println(unsafe.Sizeof(T2{})) // 16
}
</code></pre>
</div>

<a class="anchor" id="new-function"></a>
<h3>
	Is <code>new(T)</code> a sugar of <code>var t T; (&amp;t)</code>?
</h3>

<p>
Generally we can think so, though there would some subtle differences between the two, depending on compiler implementations.
The memory block allocated by <code>new</code> may be either on stack or on heap.
</p>

<a class="anchor" id="fatal-error-deadlock"></a>
<h3>
	What does the runtime error message <code>all goroutines are asleep - deadlock</code> mean?
</h3>

<p>
The word <b><i>asleep</i></b> is not accurate here, it means
<b><i>in blocking state</i></b> in fact.
</p>

<p>
As a blocking goroutine can only be unblocked by another goroutine,
if all goroutines in a program enter blocking state,
then all of they will stay in blocking state for ever.
This means the program is deadlocked.
A normal running program is never expected to be deadlocked,
so the standard Go runtime makes the program crash and exit.
</p>

<a class="anchor" id="64-bit-alignment"></a>
<h3>
	Are 64-bit integer values guaranteed to be 64-bit aligned
	so that they can be accessed atomically?
</h3>

<p>
The addresses passed to the 64-bit functions in <code>sync/atomic</code> package
must be 64-bit aligned, otherwise, calls to these functions may panic at run time.
</p>

<p>
For the standard Go compiler and gccgo compiler,
on 64-bit architectures, 64-bit integers are guaranteed to be 64-bit aligned.
So they can be always accessed atomically without any problems.
</p>

<p>
On 32-bit architectures, 64-bit integers are only guaranteed to be 32-bit aligned.
So accessing many 64-bit integers atomically may cause panics.
However, there are some ways to guarantee some 64-bit integers to be relied upon to be 64-bit aligned.
Please read <a href="memory-layout.html#64bit-atomic-operation">memory layouts in Go</a> for details.
</p>

<!--
<div>

But following 64-bit words are guaranteed to be able to be accessed atomically:
<ul>
<li>allocated 64-bit words.</li>
<li>the first field in an allocated struct if the field is a 64-bit word.</li>
<li>the first word in the first elements of an allocated array if the word is 64-bit.</li>
</ul>
</div>

<p>
Here, an <b><i>allocated</i></b> value means the address of the value is
the start address of the memory block the value locates at.
In other words, the value is placed at the beginning of the memory block it locates at.
</p>

<p>
A qualified Go compiler should promise that
all elements in an array/slice can also be accessed atomically
if one element in the array/slice can be accessed atomically
and the element type is a 64-bit word type,
though the official documentation doesn't make this guarantee.
</p>

<div>
Example:
<pre class="line-numbers"><code class="language-go">package main

import (
	"sync/atomic"
)

type T struct {
	a uint64
	b bool
	c int64
}

type V struct {
	d byte
	t T // t.a is not the first field in V.
}

var x int64
var y [3]uint64
var z = make([]int64, 5)
var t T

var v V

func main() {
	var x2 int64
	var y2 [3]uint64
	var z2 = make([]int64, 5)
	var t2 T

	var v2 = new(V)

	// following lines are guaranteed to be safe on
	// both 64-bit and 32-bit OS.
	atomic.LoadInt64(&x)
	atomic.LoadUint64(&y[1])
	atomic.LoadInt64(&z[2])
	atomic.LoadUint64(&t.a)

	atomic.LoadInt64(&x2)
	atomic.LoadUint64(&y2[1])
	atomic.LoadInt64(&z2[2])
	atomic.LoadUint64(&t2.a)

	// the following two lines are safe on 64-bit OS
	// but may be panic on 32-bit OS
	atomic.LoadUint64(&v.t.a)
	atomic.LoadUint64(&v2.t.a)
}
</code></pre>

</div>
-->

<a class="anchor" id="atomical-assignment"></a>
<h3>
	Are assignments of values atomic operations?
</h3>

<p>
No for the standard Go compiler, even if the sizes of the assigned values are native words.
</p>

<p>
Please read <a href="https://golang.org/doc/faq#What_operations_are_atomic_What_about_mutexes">the official question</a> for more details.
</p>

<a class="anchor" id="zero-values-zero-bytes"></a>
<h3>
	Is every zero value composed of a sequence of zero bytes in memory?
</h3>

<div>
<p>
For most types, this is true.
In fact, this is compiler dependent.
For example, for the standard Go compiler,
the statement is wrong for some zero values of string types.
</p>

Evidence:
<pre class="line-numbers"><code class="language-go">package main

import (
	"unsafe"
	"fmt"
)

func main() {
	var s1 string
	fmt.Println(s1 == "") // true
	fmt.Println(*(*uintptr)(unsafe.Pointer(&s1))) // 0
	var s2 = "abc"[0:0]
	fmt.Println(s2 == "") // true
	fmt.Println(*(*uintptr)(unsafe.Pointer(&s2))) // 4869856
	fmt.Println(s1 == s2) // true
}
</code></pre>
</div>

<p>
Inversely, for all the architectures the standard Go compiler currently supports,
if all bytes in a value are zero, then the value must be a zero value of its type.
However, Go specification doesn't guarantee this.
I have heard of that on some very old processors,
nil pointers are not zero in memory.
</p>

<a class="anchor" id="function-inline"></a>
<h3>
	Does the standard Go compiler support function inline?
</h3>

<p>
Yes, the standard Go compiler supports function inline.
The compiler will inline short leaf functions, automatically.
Leaf functions are the functions which doesn't contain function calls.
The specific inline rules may change from version to version.
</p>

<div>
Currently (Go SDK 1.13), for the standard Go compiler,
<ul>
<li>there is no explicit ways to specify which functions should be inlined in user programs.</li>
<li>although <code>-gcflags "-l"</code> build option can prevent any functions being inlined,
	there is no formal ways to avoid specified functions being inlined in user programs.
	There are two informal ways (both of them might become invalid for future standard Go compiler versions):
	<ol>
	<li>you can add a line <code>//go:noinline</code> directive before a function declaration to avoid the function being inlined.</li>
	<li><span style="text-decoration:line-through;">as functions containing loop blocks will not be inlined,
		you can add a <code>for false {}</code> line in a function to avoid the function being inlined.</span>
		(This way may become invalid <a href="https://github.com/golang/go/issues/14768">since Go 1.14</a>.)
	</li>
	</ol>
</li>
</ul>
</div>

<a class="anchor" id="finalizers"></a>
<h3>
	Can I use finalizers as object destructors?
</h3>

<p>
In Go programs, we can set a finalizer function for an object by using
the <code>runtime.SetFinalizer</code> function.
Generally, the finalizer function will be called before the object is garbage collected.
But finalizers are never intended to be used as destructors of objects.
The finalizers set by <code>runtime.SetFinalizer</code> are not guaranteed to run.
So you shouldn't rely on finalizers for your program correctness.
</p>

<p>
The main intention of finalizers is for libraries maintainers to
make extra efforts to remedy the damage caused by libraries users don't use the
libraries correctly. For example, in a program, if we use the <code>os.Open</code> to open
many files but forget to close them after using them, then the program
will hold many file descriptors until the program exits. This is resource leak.
To avoid the program holding too many file descriptors, the maintainers of the
<code>os</code> package will set a finalizer on the every created <code>os.File</code>
object. The finalizer will close the file descriptor stored in the <code>os.File</code>
object. As above mentioned, the finalizers are not guaranteed to be called.
They are just used to make the extent of resource leak as small as possible.
</p>

<!-- to add best practices and more cases where finalizer doesn't work. -->

<p>
Please note, some finalizers will never get called for sure,
and sometimes setting finalizers improperly will prevent some objects from being garbage collected.
Please read the <a href="https://golang.org/pkg/runtime/#SetFinalizer">runtime.SetFinalizer function documentation</a>
to get more details.
</p>

<!-- standard packages  -->

<a class="anchor" id="get-days-of-month"></a>
<h3>
	How to get the number of days of any month by using as few code lines as possible?
</h3>

<div>
Assume the input year is a nature year and the input month is also a nature month (January is 1).
<pre class="disable-line-numbers111"><code class="language-go">days := time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()
</code></pre>
For Go time APIs, the usual month range is <code>[1, 12]</code> and the start day of each month is <code>1</code>.
The start time of a month <code>m</code> in year <code>y</code> is
<code>time.Date(y, m, 1, 0, 0, 0, 0, time.UTC)</code>.
<p>
The arguments passed to <code>time.Date</code> can be outside their usual ranges
and will be normalized during the conversion.
For example, January 32 will be converted to February 1.
</p>

Here are some <code>time.Date</code> use examples in Go:
<pre class="line-numbers"><code class="language-go">package main

import (
	"time"
	"fmt"
)

func main() {
	// 2017-02-01 00:00:00 +0000 UTC
	fmt.Println(time.Date(2017, 1, 32, 0, 0, 0, 0, time.UTC))

	// 2017-01-31 23:59:59.999999999 +0000 UTC
	fmt.Println(time.Date(2017, 1, 32, 0, 0, 0, -1, time.UTC))

	// 2017-01-31 00:00:00 +0000 UTC
	fmt.Println(time.Date(2017, 2, 0, 0, 0, 0, 0, time.UTC))

	// 2016-12-31 00:00:00 +0000 UTC
	fmt.Println(time.Date(2016, 13, 0, 0, 0, 0, 0, time.UTC))

	// 2017-02-01 00:00:00 +0000 UTC
	fmt.Println(time.Date(2016, 13, 32, 0, 0, 0, 0, time.UTC))
}
</code></pre>
</div>

<a class="anchor" id="time-sleep-after"></a>
<h3>
	What is the difference between the function call <code>time.Sleep(d)</code> and the channel receive operation <code>&lt;-time.After(d)</code>?
</h3>

<p>
The two will both pause the current goroutine execution for a certain duration.
The difference is the function call <code>time.Sleep(d)</code>
will let the current goroutine enter sleeping sub-state,
but still stay in <a href="control-flows-more.html#states-of-goroutine">running state</a>,
whereas, the channel receive operation <code>&lt;-time.After(d)</code>
will let the current goroutine enter blocking state.
</p>

<a class="anchor" id="trim"></a>
<h3>
	Calls of the <code>TrimLeft</code> and <code>TrimRight</code> functions in the <code>strings</code> and <code>bytes</code>
		standard packages often return unexpected results, are there bugs in these function implementations?
</h3>

<p>
Aha, maybe there are bugs in the implementations, but none are confirmed now.
If the return results are unexpected, it is more possible that your expectations are not correct.
</p>

<div>
There are many trim functions in <code>strings</code> and <code>bytes</code> standard packages.
These functions can be categorized into two groups:
<ol>
<li>
	<code>Trim</code>, <code>TrimLeft</code>, <code>TrimRight</code>, <code>TrimSpace</code>, <code>TrimFunc</code>, <code>TrimLeftFunc</code>, <code>TrimRightFunc</code>.
	These functions will trim all leading or trailing UTF-8-encoded Unicode code points (a.k.a. runes)
	which satisfy the specified or implied conditions (<code>TrimSpace</code> implies to trim all kinds of white spaces).
	Each of the leading or trailing runes will be checked until one doesn't satisfy the specified or implied conditions.
</li>
<li>
	<code>TrimPrefix</code>, <code>TrimSuffix</code>.
	The two functions will trim the specified prefix or suffix substrings (or subslices) as a whole.
</li>
</ol>

<p>
<a href="https://github.com/golang/go/issues/19172">Some</a>
<a href="https://github.com/golang/go/issues/18160">programmers</a>
<a href="https://github.com/golang/go/issues/14657">misused</a>
<a href="https://github.com/golang/go/issues/19371">the</a>
<code>TrimLeft</code> and <code>TrimRight</code> functions
as <code>TrimPrefix</code> and <code>TrimSuffix</code> functions when they use the trim functions the first time.
Certainly, the return results are very possible not as expected.
</p>

Example:
<pre class="line-numbers"><code class="language-go">package main

import (
	"fmt"
	"strings"
)

func main() {
	var s = "abaay森z众xbbab"
	o := fmt.Println
	o(strings.TrimPrefix(s, "ab")) // aay森z众xbbab
	o(strings.TrimSuffix(s, "ab")) // abaay森z众xbb
	o(strings.TrimLeft(s, "ab"))   // y森z众xbbab
	o(strings.TrimRight(s, "ab"))  // abaay森z众x
	o(strings.Trim(s, "ab"))       // y森z众x
	o(strings.TrimFunc(s, func(r rune) bool {
		return r < 128 // trim all ascii chars
	})) // 森z众
}
</code></pre>
</div>

<a class="anchor" id="fmt-print-println"></a>
<h3>
	What are the differences between the <code>fmt.Print</code> and <code>fmt.Println</code> functions?
</h3>

<p>
The <code>fmt.Println</code> function will always write a space between two adjacent arguments,
whereas the <code>fmt.Print</code> function will write a space between two adjacent arguments
only if both of (the concrete values of) the two adjacent arguments are not strings.
</p>

<p>
Another difference is <code>fmt.Println</code> will write
a newline character in the end,
but the <code>fmt.Print</code> function will not.
</p>

<a class="anchor" id="log-print-println"></a>
<h3>
	Is there any difference between the <code>log.Print</code> and <code>log.Println</code> functions?
</h3>

<p>
The difference between the <code>log.Print</code> and <code>log.Println</code> functions
is the sams as the first difference between the <code>fmt.Print</code> and <code>fmt.Println</code>
functions described in the last question.
</p>

<p>
Both of the two functions will write a newline character in the end.
</p>

<a class="anchor" id="fmt-print-synced"></a>
<h3>
	Are <code>fmt.Print</code>, <code>fmt.Println</code> and <code>fmt.Printf</code> functions synchronized?
</h3>

<p>
No, these functions are not synchronized.
Please use the corresponding functions in the <code>log</code> standard package instead
when synchronizations are needed.
You can call <code>log.SetFlags(0)</code> to remove the prefix from each log line.
</p>

<a class="anchor" id="print-builtin-fmt-log"></a>
<h3>
What are the differences between the built-in <code>print</code>/<code>println</code> functions and the corresponding print functions in the <code>fmt</code> and <code>log</code> standard packages?
</h3>

<div>
Besides the difference mentioned in the last question,
there are some other differences between the three sets of functions.
<ol>
<li>
	The built-in <code>print</code>/<code>println</code> functions
	will write to the standard error.
	The print functions in the <code>fmt</code> standard package
	will write to the standard output.
	The print functions in the <code>log</code> standard package
	will write to the standard error by default,
	whereas which can be configured through the
	<code>log.SetOutput</code> function.

</li>
<li>
	Calls to the built-in <code>print</code>/<code>println</code> functions
	can't take array and struct arguments.
</li>
<li>
	For an argument of a composite type,
	the built-in <code>print</code>/<code>println</code> functions
	write the addresses of the underlying value parts of the argument,
	whereas the print functions in the <code>fmt</code> and <code>log</code>
	standard packages try to write the value literal of the argument.
</li>
<li>
	Currently (Go SDK 1.13), for the standard Go compiler,
	calls to the built-in <code>print</code>/<code>println</code> functions
	will not make the values referenced by the arguments of the calls
	escape to heap, whereas the print functions in the <code>fmt</code>
	and <code>log</code> standard packages will.
</li>
<li>
	If an argument has a <code>String() string</code> or <code>Error() string</code>
	method, the print functions in the <code>fmt</code> and <code>log</code>
	standard packages will try to call that method when writing the argument,
	whereas the built-in <code>print</code>/<code>println</code> functions
	will ignore methods of arguments.
</li>
<li>
	The built-in <code>print</code>/<code>println</code> functions
	are not guaranteed to exist in future Go versions.
</li>
</ol>
</div>

<a class="anchor" id="math-crypto-rand"></a>
<h3>
	What is the difference between the random numbers produced by the <code>math/rand</code> standard package and the <code>crypto/rand</code> standard package?
</h3>

<p>
The pseudo random numbers produced by the <code>math/rand</code> standard
package are deterministic for a given seed.
The produced random numbers are not good for security-sensitive contexts.
For cryptographical security purpose, we should use the pseudo random numbers
produced by the <code>crypto/rand</code> standard package.
</p>

<a class="anchor" id="math-round"></a>
<h3>
	Why isn't there a <code>math.Round</code> function?
</h3>

<p>
There is a <code>math.Round</code> function, but only since Go 1.10.
Two new functions, <code>math.Round</code> and <code>math.RoundToEven</code>
have been added since Go 1.10.
</p>

<p>
Before Go 1.10, there is a long time in
<a href="https://github.com/golang/go/issues/4594">disputing</a> whether or not
the <code>math.Round</code> function should be added to standard package or not.
In the end, the proposal is adopted.
</p>

<!-- type system -->

<a class="anchor" id="incomparable-types"></a>
<h3>
	Which types don't support comparisons?
</h3>


<div>
Following types don't support comparisons:
<ul>
<li>map</li>
<li>slice</li>
<li>function</li>
<li>
struct types containing incomparable fields
</li>
<li>
array types with incomparable element types
</li>
</ul>
<p>
Types which don't support comparisons can't be used as the key type of map types.
</p>
</div>

<div>
Please note,
<ul>
<li>
although map, slice and function types don't support comparisons,
their values can be compared to the bare <code>nil</code> identifier.
</li>
<li>
<a href="interface.html#comparison">comparing two interface values</a>
with will panic at run time if the two dynamic types of the two interface values
are identical and incomparable.
</li>
</ul>

<p>
On why slice, map and function types don't support comparison,
please read <a href="https://golang.org/doc/faq#map_keys">this answer</a> in the official Go FAQ.
</p>

</div>

<a class="anchor" id="nil-equality"></a>
<h3>
	Why aren't two <code>nil</code> values equal sometimes?
</h3>

<p><i>
(<a href="https://golang.org/doc/faq#nil_error">The answer</a> in the official Go FAQ
may also answer this question.)
</i></p>

<div>

<p>
An interface value can be viewed as a box which is used to encapsulate non-interface values.
Only values whose types implement the type of the interface value can be boxed (encapsulated) into the interface value.
In Go, there are several kinds of types whose zero values are represented as the predeclared identifier <code>nil</code>.
An interface value boxing nothing is a zero interface value, a.k.a, a nil interface value.
However an interface value boxing a nil non-interface value doesn't box nothing, so it is not, and doesn't equal to, a nil interface value.
</p>

<p>
When comparing a nil interface value and a nil non-interface value (assume they can be compared),
the nil non-interface value will be converted to the type of the nil interface value before doing the comparison.
The conversion result is an interface value boxing a copy of the non-interface value.
The result interface value doesn't box nothing, so it is not, or doesn't equal to, the nil interface value.
</p>

<p>
Please read <a href="interface.html">interfaces in Go</a> and
<a href="nil.html">nils in Go</a> for detailed explanations.
</p>

For example:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	var pi *int = nil
	var pb *bool = nil
	var x interface{} = pi
	var y interface{} = pb
	var z interface{} = nil

	fmt.Println(x == y)   // false
	fmt.Println(x == nil) // false
	fmt.Println(y == nil) // false
	fmt.Println(x == z)   // false
	fmt.Println(y == z)   // false
}
</code></pre>
</div>

<a class="anchor" id="slice-conversion"></a>
<h3>
	Why don't type <code>[]T1</code> and <code>[]T2</code> share the same underlying type
	even if the two different types <code>T1</code> and <code>T2</code> share the same underlying type?
</h3>

<p><i>
(It looks the official Go FAQ also added <a href="https://golang.org/doc/faq#convert_slice_with_same_underlying_type">a similar question</a> not long ago.)
</i></p>

<div>
<p>
In Go, values of a slice type can be converted to another slice type
without using <a href="unsafe.html">the <code>unsafe</code> mechanisms</a> only if the two slice types
share the same <a href="type-system-overview.html#underlying-type">underlying type</a>.
(<a href="value-conversions-assignments-and-comparisons.html">This article</a>
lists the full list of value conversion rules.)
</p>

<p>
The underlying type of a non-defined composite type is the composite type itself.
So even if two different types <code>T1</code> and <code>T2</code> share the same underlying type,
type <code>[]T1</code> and <code>[]T2</code> are still different types,
so their underlying types are also different, which means values of one of them can't be converted
to the other.
</p>

The reasons for the underlying types of <code>[]T1</code> and <code>[]T2</code> are not same are:
<ul>
<li>the request of converting values of <code>[]T1</code> and <code>[]T2</code> to each other is not strong in practice.</li>
<li>to make <a href="type-system-overview.html#underlying-type">underlying type tracing rule</a> simpler.</li>
</ul>

<p>
The same reasons are also valid for other composite types.
For example, type <code>map[T]T1</code> and <code>map[T]T2</code> also don't share the same underlying type
even if <code>T1</code> and <code>T2</code> share the same underlying type.
</p>

It is possible that values of type <code>[]T1</code> can be converted to
<code>[]T2</code> by using the <code>unsafe</code> mechanisms,
but generally this is not recommended:
<pre class="line-numbers"><code class="language-go">package main

import (
	"fmt"
	"unsafe"
)

func main() {
	type MyInt int

	var a = []int{7, 8, 9}
	var b = *(*[]MyInt)(unsafe.Pointer(&a))
	b[0]= 123
	fmt.Println(a) // [123 8 9]
	fmt.Println(b) // [123 8 9]
	fmt.Printf("%T \n", a) // []int
	fmt.Printf("%T \n", b) // []main.MyInt
}
</code></pre>
</div>

<a class="anchor" id="unaddressable-values"></a>
<h3>
	Which values can and which values can't be taken addresses?
</h3>

<div>
Following values can't be taken addresses:
<ul>
<li>bytes in strings</li>
<li>map elements</li>
<li>dynamic values of interface values (exposed by type assertions)</li>
<li>constant values</li>
<li>literal values</li>
<li>package level functions</li>
<li>methods (used as function values)</li>
<li>intermediate values
	<ul>
	<li>function calls</li>
	<li>explicit value conversions</li>
	<li>all sorts of operations, excluding pointer dereference operations, but including:
		<ul>
		<li>channel receive operations</li>
		<li>sub-string operations</li>
		<li>sub-slice operations</li>
		<li>addition, subtraction, multiplication, and division, etc.</li>
		</ul>
	</li>
	</ul>
</li>
</ul>
</div>

<div class="alert alert-success">
Please note, there is a syntax sugar, <code>&amp;T{}</code>, in Go.
It is a short form of <code>tmp := T{}; (&amp;tmp)</code>.
So <code>&amp;T{}</code> is legal doesn't mean
the literal <code>T{}</code> is addressable.
</div>
<p></p>

<div>
Following values can be taken addresses:
<ul>
<li>variables</li>
<li>fields of addressable structs</li>
<li>elements of addressable arrays</li>
<li>elements of any slices (whether the slices are addressable or not)</li>
<li>pointer dereference operations</li>
</ul>
</div>

<a class="anchor" id="maps-are-unaddressable"></a>
<h3>
	Why are map elements unaddressable?
</h3>

<p>
The main reason is making map elements addressable means the address of a map element
must not be changed in its life cycle. This prevents Go compilers using more efficient
algorithms to implement map. For the standard Go compiler, the internal addresses of
map elements may be changed at run time.
</p>

<a class="anchor" id="slice-elements-always-addressable"></a>
<h3>
	Why elements of a non-nil slice are always addressable, even if the slice is unaddressable?
</h3>

<div>
The internal type for slices is a struct like
<pre class="line-numbers"><code class="language-go">struct {
	// elements references an element sequence.
	elements unsafe.Pointer
	length   int
	capacity int
}
</code></pre>
<p>
Each slice indirectly references an underlying element sequence internally.
Although a non-nil slice is not addressable,
its internal element sequence is always allocated somewhere and must be addressable.
Taking addresses of elements of a slice is taking the addresses of elements of the internal element sequence actually.
This is why elements of unaddressable non-nil slices are always addressable.
</p>
</div>

<!--p>
For the same reason, the substring operations on unaddressable strings also always compile ok
(by the standard Go compiler).
However, I can't make sure whether this is guaranteed by Go specification or not.
</p-->

<a class="anchor" id="method-set-relation"></a>
<h3>
	For any non-pointer non-interface defined type <code>T</code>,
	why is the method set of <code>*T</code> always a super set of the method set of <code>T</code>,
	but not vice versa?
</h3>

<div>
In Go, for convenience,
<ul>
<li>
	a value of type <code>T</code> can call methods defined on type <code>*T</code>,
	but only if the value of <code>T</code> are addressable.
	Compilers will take the address of the <code>T</code> value automatically
	before calling the pointer receiver methods.
	For not any values of type <code>T</code> are addressable,
	not any values of type <code>T</code> are capable of calling methods defined on type <code>*T</code>.
	This convenience is just a sugar, not an intrinsic rule.
</li>
<li>
	a value of type <code>*T</code>  can always call methods defined on type <code>T</code>.
	This is because it is always legal to dereference a pointer value.
	This convenience is not only a sugar, but also an intrinsic rule.
</li>
</ul>
<p>
So it is much reasonable that the method set of <code>*T</code> is always
a super set of the method set of <code>T</code>, but not vice versa.
</p>
</div>

<div>
In fact, you can think that, for every method declared on type <code>T</code>,
an implicit method with the same name and the same signature is automatically
declared on type <code>*T</code>.
Please read <a href="method.html#implicit-pointer-methods">methods</a> for details.

<pre class="line-numbers"><code class="language-go">func (t T) MethodX(v0 ParamType0, ...) (ResultType0, ...) {
	...
}

// An implicit method of *T is automatically defined as
func (pt *T) MethodX(v0 ParamType0, ...) (ResultType0, ...) {
	return (*pt).MethodX(v0, ...)
}
</code></pre>

<!--p>
If a method is defined on type <code>*T</code>, no methods with the same method name can
be defined on <code>T</code> any more.
This is another explanation why the method set of <code>*T</code> is always
a super set of the method set of <code>T</code>, but not vice versa.
</p-->
</div>

<p>
Please read <a href="https://golang.org/doc/faq#different_method_sets">this answer</a> in the official Go FAQ to get more explanations.
</p>

<a class="anchor" id="types-can-have-methods"></a>
<h3>
	Which types can we implement methods for?
</h3>

<p>
Please read <a href="method.html">methods in Go</a> for details.
</p>

<a class="anchor" id="declare-immutables"></a>
<h3>
	How to declare immutable values in Go?
</h3>

<div>
There are three <b><i>immutable value</i></b> definitions:
<ol>
<li>the values which have no addresses (so they are not addressable).</li>
<li>the values which have addresses but are not addressable (their addresses are not allowed to be taken in syntax).</li>
<li>the values which are addressable but their values are not allowed to be modified in syntax.</li>
</ol>

<p>
In Go, up to now (Go 1.13), there are no values satisfy the third definition.
In other words, the third definition is not supported.
</p>

<p>
Name constant values satisfy the first definition.
</p>

<p>
Methods and package-level functions can also viewed as declared immutable values.
They satisfy the second definition.
String elements (bytes) also satisfy the second definition.
</p>

<p>
There are no ways to declare other custom immutable named values in Go.
</p>
</div>

<a class="anchor" id="set-container-type"></a>
<h3>
	Why isn't there a built-in <code>set</code> container type?
</h3>

<div>
Sets are just maps but don't care about element values.
In Go, <code>map[Tkey]struct{}</code> is often used as a set type.
</div>

<a class="anchor" id="byte-rune-slice-string"></a>
<h3>
	What is byte? What is rune?
	How to convert <code>[]byte</code> and <code>[]rune</code> values to strings?
</h3>

<p>
In Go, <code>byte</code> is an alias of type <code>uint8</code>.
In other words, <code>byte</code> and <code>uint8</code> are the same identical type.
The same relation is for <code>rune</code> and <code>int32</code>.
</p>

<p>
A <code>rune</code> often is used to store a Unicode code point.
</p>

<div>
<code>[]byte</code> and <code>[]rune</code> values can be explicitly and directly converted to strings,
and vice versa.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	var s0 = "Go"

	var bs = []byte(s0)
	var s1 = string(bs)

	var rs = []rune(s0)
	var s2 = string(rs)

	fmt.Println(s0 == s1) // true
	fmt.Println(s0 == s2) // true
}
</code></pre>

<p>
About more on strings, please read <a href="string.html">strings in Go</a>.
</p>
</div>

<a class="anchor" id="pointer-atomic"></a>
<h3>
	How to manipulate pointer values atomically?
</h3>

<div>
Example:
<pre class="line-numbers"><code class="language-go">import (
	"unsafe"
	"sync/atomic"
)

type T int // just a demo

var p *T

func demo(newP *T) {
	// load
	var _ = (*T)(atomic.LoadPointer(
		(*unsafe.Pointer)(unsafe.Pointer(&p)),
		))

	// store
	atomic.StorePointer(
		(*unsafe.Pointer)(unsafe.Pointer(&p)),
		unsafe.Pointer(newP),
		)


	// swap
	var oldP = (*T)(atomic.SwapPointer(
		(*unsafe.Pointer)(unsafe.Pointer(&p)),
		unsafe.Pointer(newP),
		))

	// compare and swap
	var swapped = atomic.CompareAndSwapPointer(
		(*unsafe.Pointer)(unsafe.Pointer(&p)),
		unsafe.Pointer(oldP),
		unsafe.Pointer(newP),
		)

	_ = swapped
}
</code></pre>

<p>
Yes, now it is much verbose to use the pointer atomic functions.
</p>
</div>

<!-- others -->

<a class="anchor" id="about-iota"></a>
<h3>
	What does <code>iota</code> mean?
</h3>

<div>
Iota is the ninth letter of the Greek alphabet.
In Go, <code>iota</code> is used in constant declarations.
In each constant declaration group, its value is <code>N</code>
in the <b><i>N</i></b>th constant specification in that constant declaration group.
</div>

<a class="anchor" id="check-if-channels-closed"></a>
<h3>
	Why isn't there a built-in <code>closed</code> function to check whether or not a channel is closed?
</h3>

<p>
The reason is the usefulness of such function is very limited.
The return result of a call to such function may be not able to
reflect the latest status of the input channel argument.
So it is not a good idea to make decisions relying on the return result.
</p>

<p>
If you do need such a function, it would be effortless to write one by yourself.
Please read <a href="channel-closing.html">this article</a>
to get how to write <code>closed</code> functions and how to avoid using such a function.
</p>

<a class="anchor" id="return-local-pointers"></a>
<h3>
	Is it safe for a function to return pointers of local variables?
</h3>

<p>
Yes, it is absolutely safe in Go.
</p>

<p>
Go compilers which support stack will do escape analysis.
For the standard Go compiler, if the escape analyzer thinks a memory block
will only be used in current function call for sure, it will allocate the
memory block on stack, otherwise, then the memory block will be allocated on heap.
Please read <a href="memory-block.html">memory block</a> for more information.
</p>

<a class="anchor" id="gopher"></a>
<h3>
	What does the word <b><i>gopher</i></b> mean in Go community?
</h3>

<p>
In Go community, a <b><i>gopher</i></b> means a Go programmer.
This nickname may be originated from the fact that Go language
adopted <a href="https://blog.golang.org/gopher">a cartoon gopher</a> as the mascot.
BTW, the cartoon gopher is designed by <i>Renee French</i>,
who is the wife of the (first) Go project leader, <i>Rob Pike</i>.
</p>





</div> <!-- summaries-items -->

<!--

What are "named types"?
* obsoleted.

why pointer types with base types as pointer or interface types can't be embedded.
* The reason is, except pointer and interface types, for each type T of other types,
  the method set of *T is always a super-set of T.
  To avoid confusion, ...

explain some exceptions and details.

why left side of := must be pure identifiers?
* s, s[0] = []int{1, 2}, 1. The "s[0]" is an element of an old slice or the new slice?

why fmt.Print function makes argument escape to heap.

todo: add related go-nuts/issue links in each question.

todo: also index official faq questions.

is it possible to recover out of memory error?
* https://github.com/golang/go/issues/14162
* https://github.com/golang/go/issues/16843
* https://groups.google.com/forum/#!topic/golang-dev/wUEWhk2jtHM
* https://github.com/golang/go/blob/master/src/runtime/HACKING.md#error-handling-and-reporting

time.Format, what do 01 02 03 04 05 06 07 mean?

Why json marshal no output: fields are not exported.

in go, size type is int, not uint, why?

why Go doesn't support loop import like C++ and Java?
just a tradeoff, one of many in Go.

Why is there not a function to get the undrlying type of a type
https://groups.google.com/forum/#!searchin/golang-nuts/reflect$3A$20get$20underlying$20type|sort:relevance/golang-nuts/BJEuegjQtEA/q2S3b6JxY1MJ

https://www.reddit.com/r/golang/comments/8m4xrh/do_linux_golang_binaries_depend_on_libc/

Why type assertion with ok fail panic?
* while the design of Go tries to be consistent in a big view, there are really some inconsistencies at some details.
* history reason ...

why defined pointer type has no and can't own methods.

Why fallthrough not allowed in select and type-switch?
https://github.com/golang/go/issues/25676#issuecomment-393734800
(it is feasible if the next branch is defailt or no variables are declared,
but for consistentcy, ...)

why break and fallthrought are not allowed in type switcn and select

* why non-exported fields can be listed through reflect?
  * for a non-exported fields can have exported fields.
    Otherwise, there are no ways to listed the exported fields.

why some goto details?
* https://github.com/golang/go/issues/26058#issuecomment-501741325

https://old.reddit.com/r/golang/comments/crdwcv/is_it_possible_to_run_a_go_binaryprogram_without/
Those libraries end up using cgo and talking to the dynamic libraries that exist on the host. Use ldd <binary> to see what dynamic libraries your binary is linked against.
They do only do this for very common libraries that they expect most hosts would have (glibc / uclibc) but it is still a point of note that it's not entirely static for all stdlib
https://github.com/golang/go/issues/25670
https://github.com/golang/go/issues/33673 : for cross-compilation CGO_ENABLED is default to 0.

FAQ:
* why non-exported fileds can be listed through reflect?
  * for a non-exported fileds can have exported fileds.
    Otherwise, there are no ways to listed the exported fileds.

* Does the the addresses of a Go value never change in its life?
  This is compiler and compiler version dependent.
* Is the standard pakcages standard?
  Not quite.
  To some extend, the standard pakcages are bound to the go tool chain destributed with them together.
  https://stackoverflow.com/questions/22195919/does-go-guarantee-constant-addresses
  * wg align
  * atomic order guarantee

What are the differences between type definition declarations and type alias declarations?
* direct method set not obtained for definition
* defined pointer type whose base is interface and pointer can't be embedded
* method receiver with alias will decalre the method on the rrepresented type

What's the difference between using panic and os.Exit to exit a program?
   The deferred calls will be invoked
   after panicking, but not os.Exited.
Note: log.Fatal functions call os.Exit.

-->

